import { AddRoleModel } from "@/api/role/RoleModel"
import { Result } from "@/http/request"
import { EditType } from "@/type/BaseEnum"
import { ref } from "vue"
import { addRoleApi, editRoleApi, deleteRoleApi } from "@/api/role/role"
import useInstance from "@/hooks/useInstance"
export default function useRole(getRoleList) {
  // 全局引入
  const { global } = useInstance()
  // ref 这种写法是最标准的可以携带类型提示的方法，还有一种简化的写法
  // const addRoleRef = ref() 但是这中写法，在使用addRoleRef.value再点的时候，不会有任何的提示
  // 需要自己接着往下写
  const addRoleRef = ref<{ show: (type: string, row?: AddRoleModel) => void }>()
  //分配权限弹框的ref属性
  const assignMenuRef = ref<{ show: (roleId: string, name: string) => void }>()
  // 新增
  const addBtn = () => {
    addRoleRef.value?.show(EditType.ADD)
  }
  // 编辑
  const editBtn = (row: AddRoleModel) => {
    // console.log('触发了编辑效果', row);
    // 这里不要忘记把表格的数据row传递过去
    addRoleRef.value?.show(EditType.EDIT, row)
  }
  // 删除
  const deleteBtn = async (id: number) => {
    let parm = {
      id: id
    }
    //信息确认
    let confirm = await global.$myconfirm('确定删除该数据吗?')
    if (confirm) {
      let res = await deleteRoleApi(parm)
      if (res && res.code == 200) {
        //信息提示
        global.$message({ message: res.msg, type: 'success' })
        //刷新表格
        getRoleList();

      }
    }
  }
  // 保存
  const save = async (parm: AddRoleModel) => {
    console.log('接收到的参数', parm);
    let res: Result
    if (parm.type == EditType.ADD) {
      res = await addRoleApi(parm)
    } else {
      res = await editRoleApi(parm)
    }
    if (res && res.code == 200) {
      //信息提示
      global.$message({ message: res.msg, type: 'success' })
      //刷新表格
      getRoleList();
    }
  }
  // 分配权限
  const assignPermission = (roleId: string, name: string) => {
    assignMenuRef.value?.show(roleId, name)
  }
  return {
    addBtn,
    editBtn,
    deleteBtn,
    save,
    assignPermission,
    addRoleRef,
    assignMenuRef
  }
}